package com.taotao.portal.service.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import com.taotao.po.TbItem;
import com.taotao.po.TbItemDesc;
import com.taotao.pojo.TaotaoResult;
import com.taotao.portal.service.ItemDetailService;
import com.taotao.portal.service.StaticPageService;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Service
public class StaticPageServiceImpl implements StaticPageService {

	@Autowired
	private ItemDetailService itemDetailService;
	
	@Autowired
	private FreeMarkerConfig freeMakerConfig;
	
	@Value("${STATIC_PAGE_PATH}")
	private String STATIC_PAGE_PATH;
	
	@Override
	public TaotaoResult generateItemInfoHtml(Long itemId) throws Exception {
		
		// 因为我们生成静态 就不需要异步加载。全部取得	
		TbItem item = itemDetailService.getItemInfoById(itemId);
		TbItemDesc itemDesc = itemDetailService.getItemDescById(itemId);
		String itemParamItem = itemDetailService.getItemParamItemById(itemId);
		// 获取configuration
		Configuration configuration = freeMakerConfig.getConfiguration();
		Template template = configuration.getTemplate("item.ftl");
		// 创建数据集
		Map root = new HashMap<>();
		// 向数据集中添加属性
		root.put("item", item);
		root.put("itemDesc", itemDesc.getItemDesc());
		root.put("itemParam", itemParamItem);
		// 创建一个Write对象
		Writer out= new FileWriter(new File(STATIC_PAGE_PATH+itemId+".html"));
		// 生成静态文件
		template.process(root, out);
		// 关闭刷新流
		out.flush();
		out.close();
		return TaotaoResult.ok();
	}

}
